import React from "react"
import GpContainer from "@/components/GpContainer"
import clsx from "clsx"
import Taro from "@tarojs/taro"
import { View, Image, Button, ScrollView } from "@tarojs/components"
import shareImg from "@/images/common/share.png"
import { getContentColumn } from "@/apis/index"
// import { setPageMeta } from "@/utils/common"
import { Sticky } from "@taroify/core"
import styles from "./index.module.scss"
import { handleBlockNavigation } from "@/utils/app"
import { FlowModuleJumpType, JumpPageType } from "@/types/enum"

type IState = {
  detailData: IApiRelative.IGetContentColumn.IResData
  curWikiScroll: string
  wikiScrolls: IWikiScroll[]
}
type IData = {
  options: Recordable
  wikiTriggered: boolean
  handleScrollTriggered: boolean
  wikiStickyHeight: number
}
type IWikiScroll = {
  text: string
  selector: string
  scrollTop: number
}
const selectorPrefix = "sel_"
/**
 * 专栏(原内容专题)
 * @page ContentColumn
 * @routeParams { id: number } 专栏id
 */
export default class ContentColumn extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      detailData: { moduleList: [] } as any,
      curWikiScroll: "",
      wikiScrolls: []
    }
    this.extData = {
      options: {},
      wikiTriggered: false,
      handleScrollTriggered: false,
      wikiStickyHeight: 0
    }
  }
  onLoad(options: Recordable) {
    this.extData.options = options
    this.fetchData()
  }
  onReady() {
    Taro.eventCenter.once("dataFetched", this.doLayoutComputition)
  }
  fetchData = () => {
    Taro.showLoading()
    return getContentColumn({
      id: Number(this.extData.options.id)
    })
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          let curWikiScroll = ""
          const _wikiScrolls: IWikiScroll[] = [] as IWikiScroll[]
          ;(retData.moduleList || []).forEach(l => {
            l.selector = this.getSelector(l.id)
            _wikiScrolls.push({
              text: l.title,
              selector: l.selector,
              scrollTop: 0
            })
          })
          // fallback
          if (_wikiScrolls.length > 0) {
            curWikiScroll = _wikiScrolls[0].selector
          }
          this.setState(
            {
              wikiScrolls: _wikiScrolls,
              curWikiScroll,
              detailData: res.data.data
            },
            () => {
              Taro.nextTick(() => {
                Taro.eventCenter.trigger("dataFetched")
              })
            }
          )
          this.setPageInfo(res.data.data)
        }
      })
      .finally(() => {
        this.extData.wikiTriggered = true
        Taro.hideLoading()
      })
  }
  doLayoutComputition = () => {
    this.getWikiStickyHeight().finally(() => {
      this.flushScrollTop()
    })
  }
  getWikiStickyHeight = () => {
    return new Promise(resolve => {
      const query = Taro.createSelectorQuery()
      query
        .select("#wiki-scroll-container")
        .boundingClientRect(res => {
          console.log("getWikiStickyTop", res.height)
          this.extData.wikiStickyHeight = res.height
          resolve(null)
        })
        .exec()
    })
  }
  flushScrollTop = () => {
    const wikiScrolls = this.state.wikiScrolls.concat()
    const query = Taro.createSelectorQuery()
    console.log("wikiScrollsleng", wikiScrolls.length)
    for (let i = 0; i < wikiScrolls.length; i++) {
      query.select("#" + wikiScrolls[i].selector).boundingClientRect()
    }
    query.exec(res => {
      console.log("flushScrollTop", res)
      const wikiStickyHeight = this.extData.wikiStickyHeight
      for (let i = 0; i < res.length; i++) {
        wikiScrolls[i].scrollTop = res[i].top - wikiStickyHeight
      }
      this.setState({
        wikiScrolls
      })
      console.log("wikiScrolls---", wikiScrolls)
    })
  }
  pageScrollHandler(options: Taro.PageScrollObject) {
    if (this.extData.handleScrollTriggered) return
    const { scrollTop } = options
    const { wikiScrolls } = this.state
    let curSelect: any = null
    // wikiScrolls中的scrollTop理论上是从小到大的, 但是比较需要从大往小比
    for (let i = wikiScrolls.length - 1; i >= 0; i--) {
      const cur = wikiScrolls[i]
      if (scrollTop >= cur.scrollTop) {
        curSelect = cur.selector
        break
      }
    }
    if (curSelect !== null) {
      this.setState({
        curWikiScroll: curSelect
      })
    }
  }
  onPageScroll(options: Taro.PageScrollObject) {
    if (this.extData.handleScrollTriggered) return
    this.pageScrollHandler(options)
  }
  handleWikiScrollChange = (item: IWikiScroll) => {
    this.extData.handleScrollTriggered = true
    Taro.pageScrollTo({
      scrollTop: item.scrollTop,
      duration: 300
    })
    setTimeout(() => {
      this.setState({
        curWikiScroll: item.selector
      })
      console.log("this.extData.handleScrollTriggered = false")
      this.extData.handleScrollTriggered = false
    }, 600)
  }
  onShareAppMessage() {
    return {
      title: this.state.detailData.title,
      imageUrl: this.state.detailData.pic
    }
  }
  componentDidShow() {
    this.setPageInfo(this.state.detailData)
  }
  setPageInfo = (detail: IApiRelative.IGetContentColumn.IResData) => {
    if (detail) {
      // setPageMeta({
      //     keywords: "",
      //     title: `${detail.title}-择艺宝`,
      //     description: detail.pureContent
      // })
    }
  }
  getSelector = (key: number) => {
    return selectorPrefix + key
  }
  handleBlockClick = (
    item: IApiRelative.IGetContentColumn.IResData["moduleList"][number]["contentList"][number]
  ) => {
    let extraQuery: Recordable<string | number> | undefined
    if (item.type === JumpPageType.Meiqia) {
      extraQuery = {
        sourceTitle: item.title
      }
    }
    handleBlockNavigation(
      {
        jumpPageId: item.relationId,
        jumpPageType: item.type,
        jumpType: FlowModuleJumpType.Miniprogram,
        jumpUrl: ""
      },
      extraQuery
    )
  }
  render() {
    const { detailData, wikiScrolls, curWikiScroll } = this.state
    return (
      <GpContainer>
        <View>
          <View className={styles.banner}>
            <Image src={detailData.pic} mode="scaleToFill" className={styles.bannerImg} />
            <View
              style={{
                position: "absolute",
                background: "rgba(0, 0, 0, 0.4)",
                left: 0,
                top: 0,
                right: 0,
                bottom: 0,
                zIndex: 0
              }}
            ></View>
            <View className={styles.bannerContent}>
              <View className={styles.bannerTitle}>{detailData.title}</View>
              <View className={clsx(styles.bannerDesc, "ellipse_3")}>{detailData.desc}</View>
            </View>
            <Button openType="share" className={styles.shareBtn}>
              <Image src={shareImg} mode="aspectFill" className={styles.shareImg} />
              <View className={styles.shareText}>分享</View>
            </Button>
          </View>
          <View className={styles.mainContent}>
            {/* 滚动锚点 */}
            <Sticky>
              <View className={styles.scrollViewWrap} id="wiki-scroll-container">
                <ScrollView scrollX scrollWithAnimation className={styles.scrollView}>
                  {wikiScrolls.map(item => (
                    <View key={item.selector} className="inline-block">
                      <View
                        className={clsx(styles.scrollItem, {
                          [styles["active"]]: curWikiScroll === item.selector
                        })}
                        onClick={() => this.handleWikiScrollChange(item)}
                      >
                        {item.text}
                      </View>
                    </View>
                  ))}
                </ScrollView>
              </View>
            </Sticky>
            <View className={styles.columnBlocks}>
              {detailData.moduleList &&
                detailData.moduleList.map((item, index) => (
                  <View
                    key={item.id}
                    className={clsx(styles.columnBlock, {
                      [styles.color1]: index % 4 === 0,
                      [styles.color2]: index % 4 === 1,
                      [styles.color3]: index % 4 === 2,
                      [styles.color4]: index % 4 === 3
                    })}
                    id={item.selector}
                  >
                    <View className={styles.columnName}>{item.title}</View>
                    {item.contentList && (
                      <View className={styles.columnList}>
                        {item.contentList.map(l => (
                          <View
                            key={l.id}
                            className={styles.columnListItem}
                            onClick={() => this.handleBlockClick(l)}
                          >
                            {l.title}
                          </View>
                        ))}
                      </View>
                    )}
                  </View>
                ))}
            </View>
          </View>
        </View>
      </GpContainer>
    )
  }
}
